$(function () {
    window.pageNum=1;
    window.pageSize=5;
    window.keyword="";
    // 在全局作用域内创建roleIdArray
    window.roleIdArray = new Array();

    showpage()

});
//修改
$("#roleTableBody").on("click",".editBtn",function () {
    // 1.获取当前按钮的roleId
    window.roleId = $(this).attr("roleId");
    var roleName=$(this).parents("tr").children("td:eq(2)").text();
    $("#roleNameInputEdit").val(roleName);
    $("#editModal").modal("show");

})
//确认修改
$("#editModalBtn").click(function () {
    // 1.获取文本框值
    var roleName = $.trim($("#roleNameInputEdit").val());

    if(roleName.length==0) {
        layer.msg("请输入有效角色名称！");

        return ;
    }
    $.ajax({
        url:"/role/update/role",
        type:"post",
        data:{
            "id":window.roleId,
            "name":roleName
        },
        dataType:"json",
        success:function (response) {
            var result = response.result;
            if(result == "SUCCESS") {
                layer.msg("操作成功！");
                // 3.操作成功重新分页
                showpage();
            }
            if(result == "FAILED") {
                layer.msg(response.message);
            }

            // 4.不管成功还是失败，关闭模态框
            $("#editModal").modal("hide");
        }
    });
});
//实现添加
$("#addBtn").click(function () {
    $("#addModal").modal("show")
});
//确认添加
$("#addModalBtn").click(function () {
    // 1.收集文本框内容
    var roleName = $.trim($("#roleNameInput").val());
    if(roleName == null || roleName == "") {
        layer.msg("请输入有效角色名称！");
        return ;
    }
    $.ajax({
        url:"/role/save/role",
        type:"post",
        data:{
            "roleName":roleName
        },
        dataType:"json",
        success:function (response) {
            var result = response.result;
            if(result == "SUCCESS") {
                layer.msg("操作成功！");
               showpage();
                $("#roleNameInput").val("");
            }else {
                layer.msg(response.message);
            }
            $("#addModal").modal("hide")
        }
    });
});
//绑定单机按钮删除事件
    $("#batchRemoveBtn").click(function () {
        var length = $(".itemBox:checked").length;
        if (length == 0) {
            layer.msg("请选择一条数据");
            return;
        }


        $(".itemBox:checked").each(function () {
            var roleId = $(this).attr("roleid");
            window.roleIdArray.push(roleId);
        })
        // alert(window.roleIdArray);

        showRemoveConfirmModal();
    });
//单条删除
    $("#roleTableBody").on("click", ".removeBtn", function () {
        var roleid = $(this).attr("roleId")
        window.roleIdArray.push(roleid)
        showRemoveConfirmModal();
    })
    $("#confirmModalBtn").click(function () {
        var requestBody = JSON.stringify(window.roleIdArray);
        $.ajax({
            url: "/role/batch/remove",
            type: "post",
            data: requestBody,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (response) {
                var result = response.result;
                if (result == "SUCCESS") {
                    layer.msg("操作成功！");
                    // 如果删除成功，则重新调用分页方法
                    showpage();
                }
                if (result == "FAILED") {
                    layer.msg(response.message);
                }
                // 不管成功还是失败，都需要关掉模态框
                $("#confirmModal").modal("hide");

            },
            "error": function (response) {
                layer.msg(response.message);
            }
        });
    })
    $("#searchBtn").click(function () {
        // 在单击响应函数中获取文本框中输入的数据
        var keyword = $.trim($("#keywordInput").val());

        // 验证输入数据是否有效
        if (keyword == null || keyword == "") {
            // 如果无效，提示，停止函数执行
            layer.msg("请输入关键词！");
            return;
        }

        // 如果有效，赋值给window.keyword
        window.keyword = keyword;

        // 调用showPage()重新分页
        showpage();
    });
//绑定修改权限按钮单击事件
$("#roleTableBody").on("click",".checkBtn",function(){

    // 将角色id存入全局变量
    window.roleId = $(this).attr("roleId");

    $("#roleAssignAuthModal").modal("show");
    //初始化ztree
    initWholeTree();
});
    function showpage() {
        $.ajax({
            url: "/role/search/by/keyword",
            type: "post",
            data: {
                "pageNum": window.pageNum,
                "pageSize": window.pageSize,
                "keyword": window.keyword
            },
            dataType: "JSON",
            success: function (result) {
                if (result.result == "SUCCESS") {
                    //解析数据
                    $("#roleTableBody").empty()
                    //获取集合数据
                    var list = result.data.list;
                    //判断list有效
                    if (list.length == 0) {
                        $("#roleTableBody")
                            .append("<tr><td colspan='4' style='text-align:center;'>没有查询到数据！</td></tr>");
                        return;
                    } else {
                        for (var i = 0; i < list.length; i++) {
                            var role = list[i];
                            //数据
                            var numberTd = "<td>" + (i + 1) + "</td>";
                            var checkBoxTd = "<td><input roleid='" + role.id + "' class='itemBox' type='checkbox'></td>";
                            var roleNameTd = "<td>" + role.name + "</td>";

                            //按钮
                            var checkBtn = "<button roleId='"+list[i].id+"' type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check checkBtn'></i></button>";
                            var pencilBtn = "<button roleId='"+list[i].id+"' type='button' class='btn btn-primary btn-xs editBtn'><i class=' glyphicon glyphicon-pencil'></i></button>";
                            var removeBtn = "<button roleId='" + list[i].id + "' type='button' class='btn btn-danger btn-xs removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>";
                            var btnTd = "<td>" + checkBtn + "" +
                                " " + pencilBtn + " " + removeBtn + "</td>";

                            var tr = "<tr>" + numberTd + checkBoxTd + roleNameTd + btnTd + "</tr>";

                            // 将前面拼好的HTML代码追加到#roleTableBody中
                            $("#roleTableBody").append(tr);
                        }
                        //显示分页导航
                        initPagination(result.data);

                    }

                } else {
                    layer.msg(result.message);

                }

            }
        });
    }

// 声明函数封装导航条初始化操作
    function initPagination(pageIndex) {

        // 声明变量存储分页导航条显示时的属性设置
        var paginationProperties = {
            num_edge_entries: 3,        //边缘页数
            num_display_entries: 5,      //主体页数
            callback: pageselectCallback, //回调函数
            items_per_page: window.pageSize,    //每页显示数据数量，就是pageSize
            current_page: window.pageNum - 1,//当前页页码
            prev_text: "上一页",       //上一页文本
            next_text: "下一页"        //下一页文本
        };
        // 显示分页导航条
        $("#Pagination").pagination(pageIndex.total, paginationProperties);
    }

// 在每一次点击“上一页”、“下一页”、“页码”时执行这个函数跳转页面
    function pageselectCallback(pageIndex, jq) {
        // pageIndex从0开始，pageNum从1开始
        window.pageNum = pageIndex + 1;
        var keyword = window.pageNum;
        // 跳转页面
        showpage()
        return false
    }

//实现全选
// 对分页导航条显示进行初始化
    $("#summaryBox").click(function () {
        // 1.获取当前checkbox的选中状态
        var currentStatus = this.checked;
        // 2.设置itemBox的选中状态
        $(".itemBox").prop("checked", currentStatus);

    });

    function showRemoveConfirmModal() {
// 1.将模态框显示出来
        $("#confirmModal").modal("show");
//显示要删除的数据
        var requestBody = JSON.stringify(window.roleIdArray);
        // 2.发送Ajax请求
        var ajaxResult = $.ajax({
            url: "/role/get/list/by/id/list",
            type: "post",
            data: requestBody,
            contentType: "application/json;charset=UTF-8",
            dataType: "json",
            success: function (ajaxResult) {
                if (ajaxResult.result = "SUCCESS") {
                    // 5.如果成功，显示数据
                    // 3.清空#confirmModalTableBody
                    $("#confirmModalTableBody").empty();
                    // 4.填充#confirmModalTableBody
                    var roleList = ajaxResult.data;
                    for (var i = 0; i < roleList.length; i++) {
                        // 5.获取角色相关数据
                        var role = roleList[i];
                        var id = role.id;
                        var name = role.name;
                        var trHTML = "<tr><td>" + id + "</td><td>" + name + "</td></tr>";

                        // 6.执行填充
                        $("#confirmModalTableBody").append(trHTML);
                    }
                } else {
                    layer.msg(ajaxResult.message);
                    return null;
                }

            }
        })
    }
function initWholeTree() {
    var setting = {
        "data": {
            "simpleData": {
                "enable": true,
                "pIdKey": "categoryId"
            },
            "key": {
                "name": "title"
            }
        },
        "check": {
            "enable": true
        }
    };

    // 2.获取JSON数据
    $.ajax({
        "url": "/auth/assign/get/all/auth",
        "type": "post",
        "dataType": "json",
        success:function (ajaxResult) {
            if(ajaxResult.result == "FAILED") {
                layer.msg(ajaxResult.message);
                return ;
            }
            var zNodes = ajaxResult.data;
            // 3.初始化树形结构
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            //展开所有节点
            $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);

            //回显已分配权限
            // goBackAuth();
        }
    });
}